//pages/pay/SpellPay.js
// pages/myself/integral/RedeemPay.js
var Zan = require('../../dist/index');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
Page(Object.assign({}, Zan.TopTips, Zan.Switch, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    orderType: 0, // 0=送货上门，1=到店自己提
    Distributions: -1, // 后台设置的配送方式显示 0=送货上门，1=到店自提,2=两种都有
    userName: null,
    deliverAddress: null,
    userPhone: null,
    products: [],
    totalPrice: 0,
    showDialog: false,
    days: [],
    times: [],
    day: null,
    time: null,
    date: null,
    liuyan: '',
    content: "",
    orderId: null,
    orderNO: null,
    orderDesc: null,
    canPay: true,
    againPay: 0,
    isMax: false,
    store:null,
    integralRule: null,
    integral: 0,
    shop_details: {},
    dateStr: '自提时间',
    formId: '',
    count: 1,
    multiIndex: [0, 0],
    logisticsId:null,
    pickedUpId: null,
    isService: true,
    header: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    let days = getDays();
    let store = app.globalData.store;
    this.setData({ 
      days: days, 
      times: getTimes2(), 
      day: days[0],
      store: store
     });
    // 注册列表刷新事件
    WxNotificationCenter.addNotification("RefreshNotification", this.refreshNotification, this)

    try {
      var value = wx.getStorageSync('RedeemDetailsData')
      if (value) {
        // Do something with return value
        this.setData({
          products: value,
          totalPrice: value.currChangeIntegral * value.count
        })
      }
    } catch (e) {
      // Do something when catch error
    }
    console.log(this.data.products);
    network._post_json(this, api.getTenantDistribution, { storeId: this.data.store.id }, successDistribution);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("RefreshNotification", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value,
      date: new Date().getTime() + e.detail.value[0] * 24 * 60 * 60 * 1000,
      dateLink: e.detail.value[1],
      dateStr: this.data.day[0][e.detail.value[0]] + this.data.day[1][e.detail.value[1]]
    })
  },

  bindTextArea: function (e) {
    this.setData({
      content: e.detail.value
    })
  },

  /**
   * 送货上门
   */
  express: function (e) {
    if (this.data.distribution.logistics) {
      // let packingCharge = this.data.distribution.logistics.packingCharge;
      // let freight = this.data.distribution.logistics.LogisticalRrule.unifiedmoney;
      // let total = getTotal(this, this.data.products, packingCharge, freight);
      this.setData({
        // freight: freight,
        orderType: 0
      })
    } else {
      this.showZanTopTips(this.prompt, '本店不支持配送上门');
    }
  },
  express2: function () {
    this.showZanTopTips(this.prompt, '服务商品需要上门自提');
  },
  /**
   * 自提
   */
  myselfTalk: function (e) {
    console.log(this.data.distribution.pickedUp)
    if (this.data.distribution.pickedUp) {
      // let packingCharge = this.data.distribution.pickedUp.packingCharge;
      // let total = getTotal(this, this.data.products, packingCharge, 0);
      this.setData({
        orderType: 1
      })
    } else {
      this.showZanTopTips(this.prompt, '本店不支持到店自提');
    }
  },

  /**
   * 选择地址
   */
  getAddress: function (e) {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        that.setData({
          userName: res.userName,
          deliverAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo,
          userPhone: res.telNumber
        })
        
      }
    })
  },

  /**
   * 弹出框开关
   */
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog
    })
  },

  /**
   * 选择日期
   */
  chooseDay: function (e) {
    let index = e.currentTarget.dataset.index;
    for (let i = 0; i < this.data.days.length; i++) {
      if (i == index) {
        this.data.days[i].active = true;
        if (i == 0) {
          this.setData({
            times: getTimes2()
          })
        } else {
          this.setData({
            times: getTimes()
          })
        }
      } else {
        this.data.days[i].active = false;
      }
    }
    this.setData({
      days: this.data.days,
      day: this.data.days[index]
    })
  },

  /**
   * 选择时间
   */
  chooseTime: function (e) {
    let time = e.currentTarget.dataset.time;
    this.setData({
      time: time,
      date: this.data.day.date + '(' + this.data.day.week + ') ' + time.name,
      showDialog: !this.data.showDialog
    })
  },

  formIdSubmit: function (e) {
    this.setData({
      formId: e.detail.formId
    })
  },

  /**
  * 选择支付方式
  */
  createOrder: function (e) {
    let data = {};
    let products = [];
    let product = {};
    product.productId = this.data.products.product.id;
    product.count = this.data.products.count;
    product.specid = this.data.products.specId;
    products.push(product);
    data.products = products;
    data.storeId = this.data.store.id;
    // data.linkType = 2;
    data.content = this.data.content;
    data.orderType = this.data.orderType;
    if ((this.data.distribution.logistics && this.data.orderType == 0) || this.data.orderType == 2) { // 线上
      data.orderType = 0;
      data.tenantDistributionId = this.data.logisticsId;
      if (this.data.deliverAddress) {
        data.deliverAddress = this.data.deliverAddress;
        data.userName = this.data.userName;
        data.userPhone = this.data.userPhone;
        if (this.data.time) {
          data.subscribeDate = this.data.day.dateDetails + ' ' + this.data.time.name;
        }
        network._post_json(this, api.createOrder, data, success);
      } else {
        this.showZanTopTips(this.prompt, '请设置收货地址');
      }
    } else if (this.data.distribution.pickedUp && this.data.orderType == 1) { // 线下
      data.orderType = 1;
      data.tenantDistributionId = this.data.pickedUpId;
      if (this.data.time) {
        data.subscribeDate = this.data.day.dateDetails + ' ' + this.data.time.name;
        network._post_json(this, api.createOrder, data, success);
      } else {
        this.showZanTopTips(this.prompt, '请选择自提时间');
      }
    }

  }
}))

/**
 * 获得日期
 */
var getDays = function () {
  let week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  let date = utils.formatDate07(new Date());
  let time = new Date(date.replace(/-/g, '/')).getTime();
  let days = [];
  for (let i = 0; i < 4; i++) {
    let day = {};
    day.time = time + (24 * 60 * 60 * 1000) * i;
    day.active = false;
    if (i == 0) {
      day.active = true;
      day.date = '今天';
    } else if (i == 1) {
      day.date = '明天';
    } else {
      var month = new Date(day.time).getMonth() + 1;
      var day01 = new Date(day.time).getDate();
      day.date = month + '月' + day01 + '日';
    }
    day.dateDetails = utils.formatDate02(new Date(day.time));
    day.week = week[new Date(day.time).getDay()];
    days.push(day);
  }
  console.log(days);
  return days;
}

/**
 * 获取时间
 */
var getTimes = function () {
  let times = [];
  for (let i = 10; i <= 22; i++) {
    let time = {};
    time.name = i + ':00';
    time.value = i * 60 * 60 * 1000;
    times.push(time)
  }
  return times;
}
var getTimes2 = function () {
  let times = [];
  var date = new Date();
  var h = date.getHours();
  for (let i = h; i <= 22; i++) {
    let time = {};
    time.name = i + ':00';
    time.value = i * 60 * 60 * 1000;
    times.push(time)
  }
  return times;
}
// 生成订单
var success = function (that, res) {
  if(res.data.data){
    that.showZanToast('兑换成功!');
  }
  WxNotificationCenter.postNotificationName('integralRefreshNotification');
  wx.redirectTo({
    url: "/pages/myself/order/Order?index=0"
  })
}

// 修改订单
var modifySuccess = function (that, res) {
  if (res.data.message == '修改订单成功') {
    if (app.globalData.userAndTenantInfo) {
      // 购买
      network._post_json(that, api.wxPay, {
        products: that.data.products,
        appId: app.globalData.appId,
        orderId: res.data.data.orderNO,
        OrderDesc: res.data.data.orderDesc,
        totalFee: res.data.data.total
      }, wxPaySuccess);
    } else {
      app.userInfoCallback = res => {
        // 购买
        network._post_json(that, api.wxPay, {
          products: that.data.products,
          appId: app.globalData.appId,
          orderId: res.data.orderNO,
          OrderDesc: res.data.orderDesc,
          totalFee: res.data.total
        }, wxPaySuccess);
      }
    }
  }
}



var successDistribution = function (that, res) {
  that.setData({
    distribution: res.data.data,
  })
  var logistics = res.data.data.logistics;
  // 配送费
  if (logistics) {
    that.setData({
      orderType: 0,
      Distributions: 0,
    })
  }
  if (res.data.data.pickedUp) {
    that.setData({
      orderType: 1,
      Distributions: 1,
    })
  } if (logistics && res.data.data.pickedUp) {
    that.setData({
      orderType: 2,
      Distributions: 2,
    })
  }

  if (res.data.data.pickedUp) {
    if (that.data.products.product.isService == 1) {
      that.setData({
        orderType: 1,
        Distributions: 1,
        isService: false,
      })
    }
  }
  
  
}

